package com.zbkj.crmeb.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageHelper;
import com.utils.DateUtil;
import com.zbkj.crmeb.store.dao.ChannelFreeShippingActivityDao;
import com.zbkj.crmeb.store.model.ChannelFreeShippingActivity;
import com.zbkj.crmeb.store.model.ChannelFreeShippingActivityCity;
import com.zbkj.crmeb.store.model.ChannelFreeShippingActivityProduct;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.request.ChannelFreeShippingActivityRequest;
import com.zbkj.crmeb.store.response.ChannelFreeShippingActivityResponse;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.service.ChannelFreeShippingActivityCityService;
import com.zbkj.crmeb.store.service.ChannelFreeShippingActivityProductService;
import com.zbkj.crmeb.store.service.ChannelFreeShippingActivityService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.system.model.SystemCity;
import com.zbkj.crmeb.system.service.SystemCityService;
import com.zbkj.crmeb.user.model.UserAddress;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChannelFreeShippingActivityServiceImpl extends ServiceImpl<ChannelFreeShippingActivityDao, ChannelFreeShippingActivity> implements ChannelFreeShippingActivityService {

    @Autowired
    private ChannelFreeShippingActivityProductService channelFreeShippingActivityProductService;
    @Autowired
    private ChannelFreeShippingActivityCityService channelFreeShippingActivityCityService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private SystemCityService systemCityService;

    /**
     * 功能描述: 新增/修改满额包邮活动
     *
     * @Param: [request, merId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/12/30 10:39
     */
    @Override
    public Boolean saveOrUpdateActivity(ChannelFreeShippingActivityRequest request, Integer merId) {

        //是否设置全部商品 false：单独设置 true:全部商品
        boolean allProduct = CollectionUtils.isEmpty(request.getProductIds());
        //新增时判断商品情况
        if (Objects.isNull(request.getId())) {
            //进行中的满额包邮活动列表
            List<ChannelFreeShippingActivity> list = getInProcessActivities(merId);

            //列表不为空，判断是否有商品参加同类型活动
            if (CollectionUtils.isNotEmpty(list)) {
                //全部商品
                if (allProduct) {
                    //有设置过全部商品
                    if (list.stream().anyMatch(channelFreeShippingActivity -> Objects.equals(channelFreeShippingActivity.getAllProduct(), 1))) {
                        throw new CrmebException("已存在全部商品满额条件");
                    }
                } else {
                    //已经单独设置过的商品
                    List<Integer> productIds = channelFreeShippingActivityProductService.getProductIds(list.stream().map(ChannelFreeShippingActivity::getId).collect(Collectors.toList()));
                    if (CollectionUtils.isNotEmpty(productIds)) {
                        for (Integer id : request.getProductIds()) {
                            //新增的商品有正在进行中的满额包邮活动
                            if (productIds.contains(id)) {
                                throw new CrmebException("所选商品中有其他满额包邮情况，请重新选择");
                            }
                        }
                    }
                }
            }
        }

        ChannelFreeShippingActivity channelFreeShippingActivity = new ChannelFreeShippingActivity();
        channelFreeShippingActivity.setId(request.getId())
                .setActivityName(request.getActivityName())
                .setActivityTimeType(request.getActivityTimeType())
                .setPreferentialType(request.getPreferentialType())
                .setPreferentialCondition(request.getPreferentialCondition())
                .setFreeShipping(request.getFreeShipping())
                .setNotFreeAreaSetting(request.getNotFreeAreaSetting())
                .setMerId(merId);
        //活动时间段设置开始结束时间
        if (Objects.equals(request.getActivityTimeType(), 1)) {
            channelFreeShippingActivity.setActivityStartTime(DateUtil.strToDate(request.getActivityStartTime(), Constants.DATE_FORMAT));
            channelFreeShippingActivity.setActivityEndTime(DateUtil.strToDate(request.getActivityEndTime(), Constants.DATE_FORMAT));
        }
        //设置是否全部商品
        if (!allProduct) {
            channelFreeShippingActivity.setAllProduct(0);
        } else {
            channelFreeShippingActivity.setAllProduct(1);
        }
        //保存
        boolean save = this.saveOrUpdate(channelFreeShippingActivity);
        //删除该活动下配置的商品与不包邮城市
        channelFreeShippingActivityProductService.removeProductByActivityId(channelFreeShippingActivity.getId());
        channelFreeShippingActivityCityService.removeCityByActivityId(channelFreeShippingActivity.getId());

        //存在单独设置的商品
        if (!allProduct) {

            List<ChannelFreeShippingActivityProduct> channelFreeShippingActivityProducts = new ArrayList<>();
            for (Integer productId : request.getProductIds()) {
                ChannelFreeShippingActivityProduct product = new ChannelFreeShippingActivityProduct();
                product.setProductId(productId).setActivityId(channelFreeShippingActivity.getId());
                channelFreeShippingActivityProducts.add(product);
            }
            channelFreeShippingActivityProductService.saveBatch(channelFreeShippingActivityProducts);
        }

        //设置了不包邮地区
        if (request.getNotFreeAreaSetting()) {
            List<ChannelFreeShippingActivityCity> channelFreeShippingActivityCities = new ArrayList<>();
            for (Integer cityId : request.getNotFreeArea()) {
                ChannelFreeShippingActivityCity city = new ChannelFreeShippingActivityCity();
                city.setCityId(cityId).setActivityId(channelFreeShippingActivity.getId());
                channelFreeShippingActivityCities.add(city);
            }
            channelFreeShippingActivityCityService.saveBatch(channelFreeShippingActivityCities);
        }

        return save;
    }

    /**
     * 功能描述: 删除
     *
     * @Param: [activityId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/12/30 15:27
     */
    @Override
    public Boolean removeActivity(Integer activityId) {
        channelFreeShippingActivityProductService.removeProductByActivityId(activityId);
        channelFreeShippingActivityCityService.removeCityByActivityId(activityId);
        return this.removeById(activityId);
    }

    /**
     * 功能描述: 列表查询
     *
     * @Param: [activityName, request, merId]
     * @Return: java.util.List<com.zbkj.crmeb.store.response.ChannelFreeShippingActivityResponse>
     * @Author: wangzh
     * @Date: 2022/12/30 16:26
     */
    @Override
    public List<ChannelFreeShippingActivityResponse> getList(String activityName, PageParamRequest request, Integer merId) {
        List<ChannelFreeShippingActivityResponse> responses = new ArrayList<>();
        LambdaQueryWrapper<ChannelFreeShippingActivity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChannelFreeShippingActivity::getMerId, merId);
        //模糊搜索
        if (StringUtils.isNotBlank(activityName)) {
            queryWrapper.like(ChannelFreeShippingActivity::getActivityName, activityName);
        }
        PageHelper.startPage(request.getPage(), request.getLimit());
        List<ChannelFreeShippingActivity> channelFreeShippingActivities = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(channelFreeShippingActivities)) {
            return responses;
        }

        //类型转化
        for (ChannelFreeShippingActivity channelFreeShippingActivity : channelFreeShippingActivities) {
            ChannelFreeShippingActivityResponse response = new ChannelFreeShippingActivityResponse();
            BeanUtils.copyProperties(channelFreeShippingActivity, response);
            if (Objects.equals(channelFreeShippingActivity.getActivityTimeType(), 1)) {
                response.setActivityStartTime(DateUtil.dateToStr(channelFreeShippingActivity.getActivityStartTime(), Constants.DATE_FORMAT));
                response.setActivityEndTime(DateUtil.dateToStr(channelFreeShippingActivity.getActivityEndTime(), Constants.DATE_FORMAT));
            }
            responses.add(response);
        }

        return responses;
    }

    /**
     * 功能描述: 获取满额包邮活动详情
     *
     * @Param: [activityId]
     * @Return: com.zbkj.crmeb.store.response.ChannelFreeShippingActivityResponse
     * @Author: wangzh
     * @Date: 2022/12/30 16:36
     */
    @Override
    public ChannelFreeShippingActivityResponse getInfo(Integer activityId) {
        ChannelFreeShippingActivityResponse response = new ChannelFreeShippingActivityResponse();
        ChannelFreeShippingActivity one = this.getById(activityId);
        BeanUtils.copyProperties(one, response);
        if (Objects.equals(one.getActivityTimeType(), 1)) {
            response.setActivityStartTime(DateUtil.dateToStr(one.getActivityStartTime(), Constants.DATE_FORMAT));
            response.setActivityEndTime(DateUtil.dateToStr(one.getActivityEndTime(), Constants.DATE_FORMAT));
        }

        List<Integer> productIds = channelFreeShippingActivityProductService.getProductIds(Arrays.asList(activityId));
        if (CollectionUtils.isNotEmpty(productIds)) {
            List<StoreProduct> products = storeProductService.getListInIds(productIds);
            response.setProducts(products);
        }
        //获取所有城市信息
        List<Integer> cityIds = channelFreeShippingActivityCityService.getCityId(Arrays.asList(activityId));
        if (CollectionUtils.isNotEmpty(cityIds)) {
            List<SystemCity> cities = systemCityService.getCityInfoList(cityIds);
            response.setNotFreeArea(cities);
        }
        return response;
    }

    /**
     * 功能描述: 获取商户正在进行中的活动
     *
     * @Param: [merId]
     * @Return: java.util.List<com.zbkj.crmeb.store.model.ChannelFreeShippingActivity>
     * @Author: wangzh
     * @Date: 2022/12/30 13:52
     */
    @Override
    public List<ChannelFreeShippingActivity> getInProcessActivities(Integer merId) {
        return this.list(Wrappers.<ChannelFreeShippingActivity>lambdaQuery()
                .eq(ChannelFreeShippingActivity::getMerId, merId)
                .and(i -> i.eq(ChannelFreeShippingActivity::getActivityTimeType, 0)
                        .or(e -> e.eq(ChannelFreeShippingActivity::getActivityTimeType, 1)
                                .lt(ChannelFreeShippingActivity::getActivityStartTime, new Date())
                                .gt(ChannelFreeShippingActivity::getActivityEndTime, new Date()))));
    }

    /**
     * 功能描述: 获取商品满额包邮活动信息
     * @Param: [productId, merId]
     * @Return: com.zbkj.crmeb.store.model.ChannelFreeShippingActivity
     * @Author: wangzh
     * @Date: 2022/12/30 17:16
     */
    @Override
    public ChannelFreeShippingActivity getProductInfo(Integer productId, Integer merId) {
        List<ChannelFreeShippingActivity> activities = getInProcessActivities(merId);
        if (CollectionUtils.isNotEmpty(activities)) {
            List<ChannelFreeShippingActivityProduct> productList = channelFreeShippingActivityProductService.getList(activities.stream().map(ChannelFreeShippingActivity::getId).collect(Collectors.toList()));
            //商家有单独配置满额包邮信息
            if (CollectionUtils.isNotEmpty(productList)) {
                //遍历商品信息，匹配的商品，返回活动信息
                for (ChannelFreeShippingActivityProduct product : productList) {
                    if (Objects.equals(product.getProductId(), productId)) {
                        return this.getById(product.getActivityId());
                    }
                }
            }
            //没有单独配置满额包邮，查询是否配置全部商品
            //按照保存活动规则，这里只会有一个活动或没有
            List<ChannelFreeShippingActivity> collect = activities.stream().filter(channelFreeShippingActivity -> Objects.equals(channelFreeShippingActivity.getAllProduct(), 1)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                return collect.get(0);
            }
        }
        return null;
    }

    /**
     * 功能描述: 获取包邮活动包邮的活动id
     * @Param: [storeCartResponse, userAddress, merId]
     * @Return: java.util.List<java.lang.Integer>
     * @Author: wangzh
     * @Date: 2023/1/12 14:16
     */
    @Override
	public List<Integer> getFreeShippingActivityId(List<StoreCartResponse> storeCartResponse, UserAddress userAddress, Integer merId) {
        List<Integer> ids = new ArrayList<>();
        //每个活动对应的商品金额
        Map<Integer, BigDecimal> totalPriceMap = new HashMap<>();
        //每个活动对应的商品件数
        Map<Integer, Integer> totalNumber = new HashMap<>();
        //id与活动对象的映射
        Map<Integer, ChannelFreeShippingActivity> activityMap = new HashMap<>();
        for (StoreCartResponse cartResponse : storeCartResponse){
            StoreProductCartProductInfoResponse product = cartResponse.getProductInfo();
            ChannelFreeShippingActivity productInfo = getProductInfo(product.getId(), merId);
            if(Objects.isNull(productInfo)) {
            	continue;
            }
            Integer id = productInfo.getId();
            //活动总金额计算
            if (Objects.nonNull(totalPriceMap.get(id))){
                totalPriceMap.put(id, totalPriceMap.get(id).add(cartResponse.getTruePrice().multiply(new BigDecimal(cartResponse.getCartNum()))));
            } else {
                totalPriceMap.put(id, cartResponse.getTruePrice().multiply(new BigDecimal(cartResponse.getCartNum())));
            }
            //活动件数计算
            if (Objects.nonNull(totalNumber.get(id))){
                totalNumber.put(id, totalNumber.get(id) + cartResponse.getCartNum());
            } else {
                totalNumber.put(id, cartResponse.getCartNum());
            }
            //活动进行保存
            if (Objects.isNull(activityMap.get(id))){
                activityMap.put(id, productInfo);
            }
        }
        //对每个活动进行判断
        for (Map.Entry<Integer, ChannelFreeShippingActivity> entry : activityMap.entrySet()){
            //满额包邮判断
            ChannelFreeShippingActivity productInfo = entry.getValue();
            if (Objects.nonNull(productInfo)){
                if (productInfo.getFreeShipping()){
                    //满X元
                    if (Objects.equals(productInfo.getPreferentialType(), 0)){
                        if (totalPriceMap.get(entry.getKey()).compareTo(new BigDecimal(productInfo.getPreferentialCondition())) > -1){
                            ids.add(entry.getKey());
                            //不包邮地区判断
                            if (productInfo.getNotFreeAreaSetting()){
                                List<Integer> cityId = channelFreeShippingActivityCityService.getCityId(Arrays.asList(productInfo.getId()));
                                if (Objects.nonNull(userAddress) && Objects.nonNull(cityId)){
                                    //不包邮城市匹配上用户地址，移除该活动包邮
                                    if (cityId.contains(userAddress.getCityId())){
                                        ids.remove(entry.getKey());
                                    }
                                }
                            }
                        }
                    } else {
                        //满X件
                        if (totalNumber.get(entry.getKey()).compareTo(productInfo.getPreferentialCondition()) > -1){
                            ids.add(entry.getKey());
                            //不包邮地区判断
                            if (productInfo.getNotFreeAreaSetting()){
                                List<Integer> cityId = channelFreeShippingActivityCityService.getCityId(Arrays.asList(productInfo.getId()));
                                if (Objects.nonNull(userAddress) && Objects.nonNull(cityId)){
                                    if (cityId.contains(userAddress.getCityId())){
                                        ids.remove(entry.getKey());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return ids;
    }
    /**
     * 功能描述: 获取商品满额包邮活动信息
     * @Param: [productId, merId]
     * @Return: com.zbkj.crmeb.store.model.ChannelFreeShippingActivity
     * @Author: wangzh
     * @Date: 2022/12/30 17:16
     */
    @Override
    public Map<Integer, ChannelFreeShippingActivity> getStoreProductInfoMap(List<Integer> productIds, Integer merId) {
        if(CollectionUtils.isEmpty(productIds)){
            return new HashMap<>();
        }
        Map<Integer, ChannelFreeShippingActivity> map  = null;
        List<ChannelFreeShippingActivity> activities = getInProcessActivities(merId);
        if (CollectionUtils.isNotEmpty(activities)) {
            List<ChannelFreeShippingActivityProduct> productList = channelFreeShippingActivityProductService.getList(activities.stream().map(ChannelFreeShippingActivity::getId).collect(Collectors.toList()));
            //商家有单独配置满额包邮信息
            List<Integer> activityIds = new ArrayList<>();
            Map<Integer, Integer> productActivityMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(productList)) {
                //遍历商品信息，匹配的商品，返回活动信息

                for (ChannelFreeShippingActivityProduct product : productList) {
                    if (productIds.contains(product.getProductId())) {
                        activityIds.add(product.getActivityId());
                        productActivityMap.put(product.getProductId(), product.getActivityId());
                    }
                }
            }
            List<ChannelFreeShippingActivity> list = this.listByIds(activityIds);
            map  = list.stream().collect(Collectors.toMap(ChannelFreeShippingActivity::getId,
                    e -> e,
                    (v1, v2) -> v1
            ));

            //没有单独配置满额包邮，查询是否配置全部商品
            //按照保存活动规则，这里只会有一个活动或没有
            List<ChannelFreeShippingActivity> collect = activities.stream().filter(channelFreeShippingActivity -> Objects.equals(channelFreeShippingActivity.getAllProduct(), 1)).collect(Collectors.toList());
            ChannelFreeShippingActivity temp = null;
            if (CollectionUtils.isNotEmpty(collect)) {
                temp = collect.get(0);
            }
            for(Integer productId:productIds){
                Integer acId = productActivityMap.get(productId);
                ChannelFreeShippingActivity ac = map.get(acId);
                if(null == ac){
                    map.put(productId, temp);
                }
            }


        }
        return map;
    }


}
